package net.liteheaven.xblib.common.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class ImageLoadUtil {

	private static class DisplayImageOptionsUnits {
		public static DisplayImageOptionsUnits displayImageOptionsUnits = new DisplayImageOptionsUnits();
		DisplayImageOptions options = null;
		int defaultid = 0;

		public static DisplayImageOptionsUnits getIns() {
			return displayImageOptionsUnits;
		}

		public DisplayImageOptions displayImageOptions(int resId) {
			if (null != options && defaultid == resId) {
				return options;
			}
			options = new DisplayImageOptions.Builder().showStubImage(resId)
					.showImageForEmptyUri(resId).showImageOnFail(resId)
					.cacheInMemory().cacheOnDisc()
					.bitmapConfig(Bitmap.Config.RGB_565).build();
			defaultid = resId;
			return options;
		}
	}

	public static void initImageLoader(Context context) {
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				// Not necessary in common
				.build();
		ImageLoader.getInstance().init(config);
	}

	public static void display(String imgurl, ImageView imageView, int defaultPicId) {
		ImageLoader.getInstance().displayImage(
				imgurl,
				imageView,
				DisplayImageOptionsUnits.getIns().displayImageOptions(
						defaultPicId));
	}

	public static void display(String imgurl, ImageView imageView, Drawable defaultDraw) {

		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(defaultDraw).showImageOnFail(defaultDraw)
				.cacheInMemory().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		ImageLoader.getInstance().displayImage(imgurl, imageView, options);
	}

}